package com.easipass.exangeservice.monitor;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.easipass.exangeservice.MsgListener;
import com.easipass.exangeservice.MsgMonitor;
import com.easipass.exangeservice.msg.FileMsg;

/**
 * 
 * @version $Id$
 * @author itea
 * @date 2010-3-5
 */
public class FileMsgMonitor implements MsgMonitor {
	protected final Log log = LogFactory.getLog(this.getClass());
	
	public static final String PARA_MONITOR_PATH = "monitor_path";
	
	private String monitorPath;
	
	private MsgListener listener;
	
	private Timer timer;
	
	private long period = -1;
	
	private TimerTask t = new TimerTask() {
		
		@Override
		public void run() {
			scan();
		}

	};
	
	public FileMsgMonitor(String monitorPath) {
		super();
		this.monitorPath = monitorPath;
	}
	
	public synchronized void start() {
		if(timer != null)
			timer.cancel();
		timer = new Timer();
		timer.scheduleAtFixedRate(t, 1000, period);
	}

	public synchronized void stop() {
		if(timer != null)
			timer.cancel();
		timer = null;
	}

	protected void scan() {
		
		File mp = new File(monitorPath);
		if (!mp.exists() || !mp.isDirectory()) {
			log.warn(mp.getAbsolutePath() +" does not exist or is not a directory.");
			return;
		}

		for (File f : mp.listFiles()) {
			if (!f.isFile())
				continue;
			try {
				FileMsg msg = new FileMsg(f);
				if (listener != null)
					listener.onMsg(msg);
			} catch (IOException e) {
				log.error(e, e);
			}
		}
	}

	@Override
	protected void finalize() throws Throwable {
		stop();
	}
	
	public MsgListener getMsgListener() {
		return listener;
	}

	public void setMsgListener(MsgListener listener) {
		this.listener = listener;
	}
	
	public long getPeriod() {
		return period;
	}
	public void setPeriod(long period) {
		this.period = period;
	}

}
